<template>
  <div class>
    <el-form ref="hadoopFileOutput" :model="hadoopFileOutput" label-width="170px" size="mini">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="hadoopFileOutput.name"></el-input>
      </el-form-item>
      <el-tabs v-model="tabsValue" type="border-card">
        <el-tab-pane label="文件" name="file">
          <el-form-item label="文件或者目录" prop="name">
            <el-popover
              ref="fileListPopover"
              placement="bottom-start"
              trigger="click"
              v-model="srcPopover">
              <u-file ref="filepro" @setFileData="setFileData" @hook:mounted="setChildSuffix"></u-file>
            </el-popover>
            <el-input v-model="hadoopFileOutput.file.name"  v-popover:fileListPopover  placeholder="点击选择文件" style="width:100%"></el-input>
          </el-form-item>
          <el-form-item label="创建父目录" prop="create_parent_folder">
            <el-checkbox
              v-model="hadoopFileOutput.create_parent_folder"
              true-label="Y"
              false-label="N"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="启动时不创建文件" prop="do_not_open_new_file_init" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.do_not_open_new_file_init"
              true-label="Y"
              false-label="N"
              :disabled="fileNameInField"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="从字段中获取文件名?" prop="fileNameInField" v-if="false">
            <el-checkbox v-model="hadoopFileOutput.fileNameInField" true-label="Y" false-label="N"></el-checkbox>
          </el-form-item>
          <el-form-item label="文件名字段" prop="fileNameField" v-if="false">
            <el-input v-model="hadoopFileOutput.fileNameField" :disabled="fileNameField"></el-input>
          </el-form-item>
          <el-form-item label="扩展名" prop="extention" >
            <el-input v-model="hadoopFileOutput.file.extention"></el-input>
          </el-form-item>
          <el-form-item label="文件名里包含步骤数?" prop="split" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.split"
              true-label="Y"
              false-label="N"
              :disabled="fileNameInField"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="文件里包含数据分区号?" prop="haspartno" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.haspartno"
              true-label="Y"
              false-label="N"
              :disabled="fileNameInField"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="文件名里包含日期?" prop="add_date" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.add_date"
              true-label="Y"
              false-label="N"
              :disabled="data_time_format2"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="文件名里包含时间?" prop="add_time" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.add_time"
              true-label="Y"
              false-label="N"
              :disabled="data_time_format2"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="指定日期时间格式" prop="SpecifyFormat" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.SpecifyFormat"
              true-label="Y"
              false-label="N"
              :disabled="fileNameInField"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="日期时间格式" prop="date_time_format" v-if="false">
            <el-select
              v-model="hadoopFileOutput.file.date_time_format"
              filterable
              placeholder="请选择"
              @focus="getvalueFormats"
              :disabled="data_time_format"
              style="width:100%"
            >
              <el-option
                v-for="item in formatOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="false">
            <el-button type="primary" :disabled="fileNameInField" >显示文件名</el-button>
          </el-form-item>
          <el-form-item label="结果中添加文件名" prop="add_to_result_filenames" v-if="false">
            <el-checkbox
              v-model="hadoopFileOutput.file.add_to_result_filenames"
              true-label="Y"
              false-label="N"
            ></el-checkbox>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="内容" name="content">
          <el-form-item label="追加方式" prop="append">
            <el-checkbox v-model="hadoopFileOutput.file.append" true-label="Y" false-label="N"></el-checkbox>
          </el-form-item>
          <el-form-item label="分隔符" prop="separator">
            <el-input v-model="hadoopFileOutput.separator"></el-input>
          </el-form-item>
          <el-form-item label="封闭符" prop="enclosure">
            <el-input v-model="hadoopFileOutput.enclosure"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="强制在字段周围加封闭符" prop="enclosure_forced">
                <el-checkbox v-model="hadoopFileOutput.enclosure_forced" true-label="Y" false-label="N"></el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="头部" prop="header">
                <el-checkbox v-model="hadoopFileOutput.header" true-label="Y" false-label="N"></el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="尾部" prop="footer">
                <el-checkbox v-model="hadoopFileOutput.footer" true-label="Y" false-label="N"></el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="格式" prop="format">
            <el-select
              v-model="hadoopFileOutput.format"
              placeholder="请选择"
              @focus="getFormat"
              style="width:100%"
            >
              <el-option
                v-for="item in contentFormatOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="压缩" prop="compression">
            <el-select
              v-model="hadoopFileOutput.compression"
              placeholder="请选择"
              @focus="getCompression"
              style="width:100%"
            >
              <el-option
                v-for="item in compressionOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="编码" prop="encoding">
            <el-select
              v-model="hadoopFileOutput.encoding"
              placeholder="请选择"
              @focus="getEncodings"
              style="width:100%">
              <el-option
                v-for="item in encodingoptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="字段右值填充或者裁剪" prop="pad">
                <el-checkbox v-model="hadoopFileOutput.file.pad" true-label="Y" false-label="N"></el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="快速数据存储(无格式)" prop="fast_dump">
                <el-checkbox v-model="hadoopFileOutput.file.fast_dump" true-label="Y" false-label="N"></el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="分析每一行" prop="splitevery">
            <el-input v-model="hadoopFileOutput.file.splitevery"></el-input>
          </el-form-item>
          <el-form-item label="添加文件结束行" prop="endedLine">
            <el-input v-model="hadoopFileOutput.endedLine"></el-input>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="字段" name="fields">
          <template>
            <u-table
              ref="tableField"
              :tableData="hadoopFileOutput.fields"
              :tableHeader="cloumns"
              @removeObj="removeObj"
              @getStreamFieldOptions="getStreamFieldOptions"
              id="fields"
            ></u-table>
            <el-col :span="24">
              <div class="el-table-add-row" style="width:100%" @click="addObj">
                <span>+ 添加</span>
              </div>
            </el-col>
          </template>
          <div class="divBut">
            <el-button type="primary" @click="getField">获取字段</el-button>
            <el-button type="primary" >最小宽度</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button type="info"></el-button>
          <el-button
            icon="el-icon-back"
            @click="cancel">取消
            </el-button>
            <el-button
              type="primary" icon="el-icon-check"
              @click="handleSaveData()">确定
           </el-button>
      </span>
    </div>
  </div>
</template>
<script>
  /* eslint semi: ["error", "always"] */
  import API from '../../../../../api/index';
  import TableFileds from '../../../table/table-fields.vue';
  import filePopover from '../../../file/srcFiles.vue'
  import mxgraph from '../../../../../graph/VueMxGraphLoader';
  /* eslint-disable no-undef */
  /* eslint-disable no-new-object */
  /* eslint-disable no-new */
  /* eslint-disable new-cap */
  const { mxUtils, mxCodec } = mxgraph;
  export default {
    name: 'hadoopFileOutput',
    props: {
      name: String
    },
    components: {
      'u-table': TableFileds,
      'u-file': filePopover
    },
    watch: {
      'hadoopFileOutput.fileNameInField': function (val, oldvlaue) {
        const flag = val === 'Y';
        this.fileNameInField = flag;
        this.fileNameField = !flag;
        this.setDateTimeFormatStatus();
      },
      'hadoopFileOutput.file.SpecifyFormat': function (val, oldvlaue) {
        const flag = val === 'Y';
        this.SpecifyFormat = flag;
        this.setDateTimeFormatStatus();
      }
    },
    data () {
      return {
        graph: null,
        fileNameInField: false,
        fileNameField: true,
        SpecifyFormat: false,
        data_time_format: true,
        data_time_format2: false,
        srcPopover: false,
        hadoopFileOutput: {
          name: '',
          file: {
            id: '',
            name: '', // 文件名称
            source_configuration_name: '', // hadoop的id
            append: 'N',
            pad: 'N',
            fast_dump: 'N',
            splitevery: '0',
            extention: 'txt',
            split: 'N',
            haspartno: 'N',
            add_date: 'N',
            add_time: 'N',
            SpecifyFormat: 'N',
            date_time_format: '',
            add_to_result_filenames: 'Y',
            do_not_open_new_file_init: 'N'
          },
          separator: ';',
          enclosure: '"',
          enclosure_forced: 'N',
          header: 'Y',
          footer: 'N',
          format: 'DOS',
          compression: 'None',
          encoding: '',
          endedLine: '',
          create_parent_folder: 'Y',
          fileNameInField: 'N',
          fileNameField: '',
          fields: []
        },
        temp: {
          name: '',
          file: {
            id: '',
            name: '', // 文件名称
            source_configuration_name: '', // hadoop的id
            append: 'N',
            pad: 'N',
            fast_dump: 'N',
            splitevery: '0',
            extention: 'txt',
            split: 'N',
            haspartno: 'N',
            add_date: 'N',
            add_time: 'N',
            SpecifyFormat: 'N',
            date_time_format: '',
            add_to_result_filenames: 'Y',
            do_not_open_new_file_init: 'N'
          },
          separator: ';',
          enclosure: '"',
          enclosure_forced: 'N',
          header: 'Y',
          footer: 'N',
          format: 'DOS',
          compression: 'None',
          encoding: '',
          endedLine: '',
          create_parent_folder: 'Y',
          fileNameInField: 'N',
          fileNameField: '',
          fields: []
        },
        tempHadoopFileOutput: null,
        tabsValue: 'file',
        formatOptions: [],
        encodingoptions: [],
        contentFormatOptions: [],
        compressionOptions: [],
        options: [],
        cloumns: [
          { prop: 'name', label: '名称', type: 'input' },
          { prop: 'type', label: '类型', type: 'select' },
          { prop: 'format', label: '格式', type: 'select' },
          { prop: 'length', label: '长度', type: 'input' },
          { prop: 'precision', label: '精度', type: 'input' },
          { prop: 'currency', label: '货币', type: 'input' },
          { prop: 'decimal', label: '小数', type: 'input' },
          { prop: 'group', label: '分组', type: 'input' },
          { prop: 'trim_type', label: '去除空字符串方式', type: 'select' },
          { prop: 'nullif', label: 'Null', type: 'input' }
        ]
      };
    },
    methods: {
      loadData (data) {
        if (data) {
          this.$forceUpdate();
          this.hadoopFileOutput = Object.assign({}, data);
          this.tempHadoopFileOutput = Object.assign({}, data);
        }
      },
      // 保存表单数据
      handleSaveData () {
        this.$emit('savePluginData', this.hadoopFileOutput);
      },
      cancel () {
        if (this.tempHadoopFileOutput) {
          this.saveTempPluginData(this.tempHadoopFileOutput);
        } else {
          let tempdata = JSON.parse(JSON.stringify(this.temp));
          tempdata['name'] = this.hadoopFileOutput.name;
          this.saveTempPluginData(tempdata);
        }
        this.$emit('cancel');
      },
      setGraph (val) {
        this.graph = val;
      },
      // 重置表单数据
      resetFormData (stepname) {
        this.$forceUpdate();
        this.$refs['hadoopFileOutput'].resetFields();
        this.hadoopFileOutput = JSON.parse(JSON.stringify(this.temp));
        this.hadoopFileOutput.name = stepname;
      },
      Upload (param) {
        this.$set(this.hadoopFileOutput, 'filename', param.file.name);
      },
      cleanFileList (val) {
        if (!val) {
          this.tempFiles = {};
          this.$refs.upload.clearFiles();
        }
      },
      setDateTimeFormatStatus () {
        let status = true;
        let status2 = false;
        if (!this.fileNameInField && this.SpecifyFormat) {
          status = false;
        }
        if (
          this.fileNameInField ||
          (!this.fileNameInField && this.SpecifyFormat)
        ) {
          status2 = true;
        }

        this.data_time_format = status;
        this.data_time_format2 = status2;
      },
      getEncodings () {
        API.studio.encodings().then(res => {
          this.$set(this, 'encodingoptions', res.data);
        });
      },
      getCompression () {
        API.studio.compressionProviders().then(res => {
          this.$set(this, 'compressionOptions', res.data);
        });
      },
      getFormat () {
        API.studio.formats().then(res => {
          this.$set(this, 'contentFormatOptions', res.data);
        });
      },
      getvalueFormats () {
        API.studio.valueFormats({ valueMetaName: 'Date' }).then(res => {
          if (res.data) {
            this.formatOptions = res.data;
          } else {
            this.formatOptions = [];
          }
        });
      },
      async getField () {
        let streamFields = await this.getStreamField();
        if (streamFields.data !== '') {
          this.$set(this.hadoopFileOutput, 'fields', streamFields.data);
        }
      },
      async getStreamField () {
        const value = await this.getXml();
        if (this.hadoopFileOutput.name) {
          return API.trans.inputFields(value, { stepName: this.hadoopFileOutput.name });
        }
      },
      getXml () {
        this.saveTempPluginData(this.hadoopFileOutput);
        const graph = this.graph;
        const enc = new mxCodec(mxUtils.createXmlDocument());
        const node = enc.encode(graph.getModel());
        const value = mxUtils.getPrettyXml(node);
        return value;
      },
      async getStreamFieldOptions () {
        const result = this.getStreamField();
        this.$refs['tableField'].setOptions(result);
      },
      saveTempPluginData (formData) {
        this.$emit('saveTempPluginData', formData);
      },
      removeObj (index) {
        this.hadoopFileOutput.fields.splice(index, 1);
      },
      addObj () {
        this.hadoopFileOutput.fields.push({});
        this.$nextTick(() => {
          let container = this.$el.querySelector('#fields > .el-table__body-wrapper');
          container.scrollTop = container.scrollHeight;
        });
      },
      setFileData (row) {
        this.$set(this.hadoopFileOutput.file, 'name', row.filePath.substring(0, row.filePath.lastIndexOf('.')));
        this.$set(this.hadoopFileOutput.file, 'source_configuration_name', row['srcId']);
        this.$set(this.hadoopFileOutput.file, 'id', row['id']);
        this.srcPopover = false;
      },
      setChildSuffix () {
        this.$refs.filepro.setSuffix('csv');
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .el-form-item {
    margin-bottom: 10px !important;
  }
  .divBut {
    text-align: center;
    margin-top: 54px !important;
    margin-bottom: 20px !important;
  }
  .button {
    width: 110px;
    height: 40px;
    display: inline-block;
    margin-left: 20px;
    text-align: center;
    font-size: 12px;
  }
  .el-tabs >>> .el-tabs__content {
    padding: 15px !important;
  }
  .el-dialog__footer {
    margin-top: 10px;
  }
  .el-table-add-row {
    margin-top: 10px;
    width: 100%;
    border: 1px dashed #c1c1cd;
    border-radius: 3px;
    cursor: pointer;
    justify-content: center;
    display: flex;
    line-height: 34px;
  }
</style>
